/**
 * 游戏控制器类
 * 处理键盘输入
 */
export enum KeyAction {
    MOVE_LEFT = 'move_left',
    MOVE_RIGHT = 'move_right',
    MOVE_DOWN = 'move_down',
    ROTATE = 'rotate',
    HARD_DROP = 'hard_drop',
    PAUSE = 'pause',
    RESTART = 'restart'
}

export type KeyHandler = (action: KeyAction) => void;

export class GameController {
    private handler: KeyHandler | null = null;
    private keys: Set<string> = new Set();
    private keyRepeatDelay: number = 150; // 按键重复延迟（毫秒）
    private keyRepeatInterval: number = 50; // 按键重复间隔（毫秒）
    private keyTimers: Map<string, number> = new Map();

    // 键盘映射
    private keyMap: Record<string, KeyAction> = {
        'ArrowLeft': KeyAction.MOVE_LEFT,
        'ArrowRight': KeyAction.MOVE_RIGHT,
        'ArrowDown': KeyAction.MOVE_DOWN,
        'ArrowUp': KeyAction.ROTATE,
        'KeyA': KeyAction.MOVE_LEFT,
        'KeyD': KeyAction.MOVE_RIGHT,
        'KeyS': KeyAction.MOVE_DOWN,
        'KeyW': KeyAction.ROTATE,
        'Space': KeyAction.HARD_DROP,
        'KeyP': KeyAction.PAUSE,
        'KeyR': KeyAction.RESTART
    };

    constructor() {
        this.bindEvents();
    }

    /**
     * 绑定键盘事件
     */
    private bindEvents(): void {
        window.addEventListener('keydown', (e) => this.handleKeyDown(e));
        window.addEventListener('keyup', (e) => this.handleKeyUp(e));
    }

    /**
     * 处理按键按下
     */
    private handleKeyDown(event: KeyboardEvent): void {
        const action = this.keyMap[event.code];
        if (!action || this.keys.has(event.code)) {
            return; // 忽略未映射的按键或已按下的键
        }

        this.keys.add(event.code);

        // 立即执行一次
        if (this.handler) {
            this.handler(action);
        }

        // 设置重复按键（只对移动和下降操作）
        if (action === KeyAction.MOVE_LEFT || 
            action === KeyAction.MOVE_RIGHT || 
            action === KeyAction.MOVE_DOWN) {
            this.keyTimers.set(event.code, window.setTimeout(() => {
                const intervalId = window.setInterval(() => {
                    if (this.keys.has(event.code) && this.handler) {
                        this.handler(action);
                    } else {
                        window.clearInterval(intervalId);
                    }
                }, this.keyRepeatInterval);
                this.keyTimers.set(event.code, intervalId as unknown as number);
            }, this.keyRepeatDelay));
        }

        event.preventDefault();
    }

    /**
     * 处理按键释放
     */
    private handleKeyUp(event: KeyboardEvent): void {
        const code = event.code;
        if (this.keyTimers.has(code)) {
            const timer = this.keyTimers.get(code);
            if (timer) {
                window.clearTimeout(timer);
                window.clearInterval(timer);
            }
            this.keyTimers.delete(code);
        }
        this.keys.delete(code);
    }

    /**
     * 设置按键处理函数
     */
    setHandler(handler: KeyHandler): void {
        this.handler = handler;
    }

    /**
     * 移除按键处理函数
     */
    removeHandler(): void {
        this.handler = null;
    }

    /**
     * 清理资源
     */
    destroy(): void {
        this.keys.clear();
        this.keyTimers.forEach(timer => {
            window.clearTimeout(timer);
            window.clearInterval(timer);
        });
        this.keyTimers.clear();
        this.removeHandler();
    }
}

